﻿@using Volo.Abp.Localization
@using System.Globalization
@using System.Collections.Immutable
@using Microsoft.AspNetCore.RequestLocalization
@inject ILanguageProvider LanguageProvider
@inject NavigationManager NavigationManager
@inject IAbpRequestLocalizationOptionsProvider RequestLocalizationOptionsProvider
@if (_otherLanguages != null && _otherLanguages.Any())
{
    <BarDropdown RightAligned="true">
        <BarDropdownToggle>
            @_currentLanguage.DisplayName
        </BarDropdownToggle>
        <BarDropdownMenu>
            @foreach (var language in _otherLanguages)
            {
                <BarDropdownItem Clicked="() => ChangeLanguage(language)">@language.DisplayName</BarDropdownItem>
            }
        </BarDropdownMenu>
    </BarDropdown>
}
@code {
    private IReadOnlyList<LanguageInfo> _otherLanguages;
    private LanguageInfo _currentLanguage;

    protected override async Task OnInitializedAsync()
    {
        var languages = await LanguageProvider.GetLanguagesAsync();
        var currentLanguage = languages.FindByCulture(
            CultureInfo.CurrentCulture.Name,
            CultureInfo.CurrentUICulture.Name
            );

        if (currentLanguage == null)
        {
            var localizationOptions = await RequestLocalizationOptionsProvider.GetLocalizationOptionsAsync();
            if (localizationOptions.DefaultRequestCulture != null)
            {
                currentLanguage = new LanguageInfo(
                    localizationOptions.DefaultRequestCulture.Culture.Name,
                    localizationOptions.DefaultRequestCulture.UICulture.Name,
                    localizationOptions.DefaultRequestCulture.UICulture.DisplayName);
            }
            else
            {
                currentLanguage = new LanguageInfo(
                    CultureInfo.CurrentCulture.Name,
                    CultureInfo.CurrentUICulture.Name,
                    CultureInfo.CurrentUICulture.DisplayName);
            }
        }

        _currentLanguage = currentLanguage;
        _otherLanguages = languages.Where(l => l != _currentLanguage).ToImmutableList();
    }

    private void ChangeLanguage(LanguageInfo language)
    {
        var relativeUrl = NavigationManager.Uri.RemovePreFix(NavigationManager.BaseUri).EnsureStartsWith('/').EnsureStartsWith('~');

        NavigationManager.NavigateTo(
            $"Abp/Languages/Switch?culture={language.CultureName}&uiCulture={language.UiCultureName}&returnUrl={relativeUrl}",
            forceLoad: true
        );
    }
}
